import { Router } from 'express';
import { groupcrud, cardcrud, relactionTool, materialcrud } from '../service/mjconf/__init__';
import { uploadImg } from '../utils/upload';
import { ParameterError, AuthError } from '../utils/classModal';

const router = Router();

router.use((req, { locals: { level } }, next) => {
	if (![999, 9].includes(level)) throw new AuthError();
	next();
});

router.param('id', (req, res, next, id) => {
	if (!/^(\d+)$/.test(id)) throw new ParameterError();
	next();
});

// 牌组
router
	.route('/group')
	.get(groupcrud.getlist) // 列表
	.post(groupcrud.add); // 增加
router
	.route('/group/:id')
	.get(groupcrud.getdetail) // 详情
	.put(groupcrud.change) // 改
	.delete(groupcrud.delete); // 删

// 牌型
router
	.route('/card')
	.get(cardcrud.getlist) // 列表
	.post(cardcrud.add); // 增加
router
	.route('/card/:id')
	.get(cardcrud.getdetail) // 详情
	// .put(cardcrud.change) // 改
	.delete(cardcrud.delete); // 删

// 牌组 && 牌型
router.route('/grouprelaction').delete(relactionTool.delete).post(relactionTool.add);
const relactionRouter = (() => {
	const router = Router();
	router.post('', relactionTool.batchadd);
	router.post('/sort', relactionTool.setweight); // 排序
	router.delete('/:group_id/clear', relactionTool.clear); // 清空
	return router;
})();
router.use('/grouprelaction', relactionRouter);

// 素材
router.get('/material', materialcrud.getlist); // 列表

router.post('/material', uploadImg, materialcrud.add); // 增加 id=>type
router
	.route('/material/:id')
	.get(materialcrud.getdetail) // 详情
	.put(materialcrud.change) // 改
	.delete(materialcrud.delete); // 删

module.exports = router;
